package com.yule.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yule.system.home.CorpInfoHome;
import com.yule.system.model.CorpInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@EnableScheduling
public class InitTargetDataSources {

    @Autowired
    private CorpInfoHome corpInfoHome;

    /**
     * 周期性的读取
     */
    //@Scheduled(cron = "0 */1 * * * ?")
    public void readDataSourcePeriodically() {
        setDataSourceInfo();
    }

    private void setDataSourceInfo() {
        DynamicDataSourceContext.setDBType("default");
        List<CorpInfo> list = corpInfoHome.findAll();
        //使用自己设置的sourceName作为数据源的key，使用这个进行切换
        Map<Object, Object> dataSourceMap = list.stream().collect(Collectors.toMap(x -> x.getLoginCorpName(), x -> {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(x.getDriverClassName());
            druidDataSource.setUrl(x.getDatasourceUrl());
            druidDataSource.setUsername(x.getDatasourceUsername());
            druidDataSource.setPassword(x.getDatasourcePassword());
            druidDataSource.setValidationQuery("SELECT 1 FROM DUAL");
            druidDataSource.setKeepAlive(true);
            return druidDataSource;
        }));
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
        Map<Object, Object> map = dynamicDataSource.getDataSourceMap();
        map.putAll(dataSourceMap);
        dynamicDataSource.setTargetDataSources(map);
        dynamicDataSource.afterPropertiesSet();
    }
}
